<template>
    <div class="tcenter">
        <el-form :model="userData">
            <el-form-item label="昵称">
                <el-input v-model="userData.username" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="userData.email" />
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="userData.password" type="password" />
            </el-form-item>
            <el-form-item label="重复密码">
                <el-input type="password" v-model="repeatPwd" />
            </el-form-item>
            <el-button type="warning" @click="register()">注册</el-button>
        </el-form>
    </div>
</template>
  
<script setup>
import api from '@/api/api';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const router = new useRouter();

const userData = ref({
    username: '',
    email: '',
    password: ''
})
const repeatPwd = ref('');

const register = () => {
    if (userData.value.username == '' || userData.value.email == '' || userData.value.password == '' || repeatPwd.value == '') {
        ElMessage({
            message: '内容不能为空',
            type: 'error'
        })
    }
    else if (userData.value.password != repeatPwd.value) {
        ElMessage({
            message: '两次密码不一致',
            type: 'error'
        })
    }
    else if (/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(userData.value.email) != true) {
        ElMessage({
            message: '无效的邮箱',
            type: 'error'
        })
    }
    else {
        api.userRegister(userData)
            .then(ret => {
                if (ret.flag) {
                    ElMessage({
                        message: '注册成功',
                        type: 'success'
                    })
                }
                setTimeout(() => {
                    router.push({ name: 'login' });
                }, 1500);
            })
            .catch(error => {
                ElMessage({
                    message: error,
                    type: 'error'
                })
                userData.username = ''
                userData.email = ''
                userData.password = ''
            })
    }
}

</script>

<style scoped>
.el-input {
    width: 250px;
}

.tcenter {
    width: 300px;
    margin: 0px auto;
}
</style>
  